<?php

namespace app\site\service\store;

use app\model\store\Goods;
use app\model\store\GoodsCateRel;
use app\model\store\GoodsSku;
use app\model\store\GoodsSkuSpecRel;
use app\model\store\GoodsSpec;
use app\model\store\GoodsSpecValue;
use app\model\store\GoodsTagRel;
use app\site\service\traits\InstanceTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\facade\Db;

class GoodsService extends \app\site\service\SiteBaseService
{
    use InstanceTrait;

    protected int|bool $whereShowType = false;
    protected array $whereCateId = [];
    protected int $whereTagId = 0;
    protected string $whereTitle = '';

    function initialize()
    {
        $this->model = new Goods();
    }

    function formatData(array $data): array
    {
        return $data;
    }

    function query() : Query
    {

        $query = $this->setAlias("g")->setWith([
            'cates',
            'tags',
            'skus'=>['specRels'],
            'specs'=> function($query){
                $query->with(['values'=>function($query){
                    // 向values中添加一个虚拟id:vir_id，作为唯一标记
                    // **重要**：这里不要加 vir_ 作为前缀，防止与前端添加的虚拟id冲突
                    $query->filter(function ($val) {
                        $val->vir_id = $val->id;
                    });
                }])->filter(function ($v){
                    // 添加虚拟id，
                    // **重要**：这里不要加 vir_ 作为前缀，防止与前端添加的虚拟id冲突
                    $v->vir_id = $v->id;
                });
            }
        ])->makeQuery();

        $cateIds = $this->whereCateId;
        $tagId = $this->whereTagId;
//        $tagId = $where['tagId']??'';

        if (count($cateIds) > 0){
            $query->field("g.*, gcr.cate_id")->leftJoin('goods_cate_rel gcr', 'g.id=gcr.goods_id')->where('gcr.cate_id', 'in', $cateIds);
        }
//        if (count($tagIds) > 0){
//            $query->field("g.*, gtr.tag_id")->leftJoin('goods_tag_rel gtr', 'g.id=gtr.goods_id')->where('gtr.tag_id', 'in', $tagIds);
//        }
        if ($tagId != 0){
            $query->field("g.*, gtr.tag_id")->leftJoin('goods_tag_rel gtr', 'g.id=gtr.goods_id')->where('gtr.tag_id', $tagId);
        }
        if (count($this->where)){
            $query->where($this->where);
        }

        $query->group('g.id')->filter(function ($v) {
            $cateIds = [];
            foreach ($v->cates as $cate){
                $cateIds[] = $cate->id;
            }
            $tagIds = [];
            foreach ($v->tags as $val){
                $tagIds[] = $val->id;
            }
            $v['cate_ids'] = $cateIds;
            $v['tag_ids']  = $tagIds;

            $v->imageArr = miExplode($v['images']);
            $v->image = $v['imageArr'][0];
            $v->showPrice = round($v->price??0,2);
            $v->showLinePrice = round($v->line_price??0,2);
        });

        return $query;
    }


    /**
     * 这里传入cateId或id数组
     * @param array|int $cate_id
     * @return $this
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function setWhereCateId(array|int $cate_id): static
    {
        if ($cate_id != 0){ // 分类id为0，不添加查询条件
            // 组装分类条件
            $cateSer =  GoodsCateService::instance();
            $cates = $cateSer->select();
            $cateIds = [];
            if (is_array($cate_id)){
                foreach($cate_id as $v){
                    $_cateIds = $cateSer->childrenIds($cates, $v);
                    $cateIds = array_merge($_cateIds, $cateIds);
                    // 追加当前分类
                    $cateIds[] = $v;
                }
            }else{
                $_cateIds = $cateSer->childrenIds($cates, $cate_id);
                $cateIds = array_merge($_cateIds, $cateIds);
                // 追加当前分类
                $cateIds[] = $cate_id;
            }
            $this->whereCateId = $cateIds;
        }
        return $this;

    }


    public function setWhereTagId(int $tagId): static
    {
        if ($tagId !=0){
            $this->whereTagId = $tagId;
        }
        return $this;
    }


    public function delete()
    {

        $list = $this->query()->select();

        Db::transaction(function () use ($list) {
            foreach ($list as $v){
                if ($this->force){
                    $v->force()->delete();
                    // 删除关联分类
                    GoodsCateRel::where('goods_id', $v->id)->delete();
                    // 删除关联标签
                    GoodsTagRel::where('goods_id', $v->id)->delete();
                    // 删除sku
                    GoodsSku::where('goods_id', $v->id)->delete();
                    // 删除规格
                    GoodsSpec::where('goods_id', $v->id)->delete();
                    // 删除规格值
                    GoodsSpecValue::where('goods_id', $v->id)->delete();
                    // 删除规格和sku的关联
                    GoodsSkuSpecRel::where('goods_id', $v->id)->delete();
                }
            }
        });

        return true;
    }
}
